package com.example.myshortcutdemo.appwidget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import com.example.myshortcutdemo.R

/**
 * @author tgw
 * @date 2022/5/6
 * @describe
 */
class ExampleAppWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        Log.d("自定义的", "onUpdate:ExampleAppWidgetProvider ")
        // Perform this loop procedure for each App Widget that belongs to this provider
        appWidgetIds.forEach { appWidgetId ->
            // Create an Intent to launch ExampleActivity
            val pendingIntent: PendingIntent = Intent(context, AppWidgetExamapleActivity::class.java)
                .let { intent ->
                    PendingIntent.getActivity(context, 0, intent,  PendingIntent.FLAG_UPDATE_CURRENT)
                }

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            val views: RemoteViews = RemoteViews(
                context.packageName,
                R.layout.appwidget_provider_layout
            ).apply {
                setOnClickPendingIntent(R.id.button, pendingIntent)
            }

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }
}

class WidgetProvider : AppWidgetProvider() {
    // 每接收一次广播消息就调用一次，使用频繁
    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
        Log.d("自定义的", "onReceive--: ")
    }

    // 每次更新都调用一次该方法，使用频繁
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        Log.d("自定义的", "onUpdate--: ")
    }

    // 每删除一个就调用一次
    override fun onDeleted(context: Context, appWidgetIds: IntArray) {
        super.onDeleted(context, appWidgetIds)
        Log.d("自定义的", "onDeleted--: ")
    }

    // 当该Widget第一次添加到桌面是调用该方法，可添加多次但只第一次调用
    override fun onEnabled(context: Context) {
        super.onEnabled(context)
        Log.d("自定义的", "onEnabled--: ")
    }

    // 当最后一个该Widget删除是调用该方法，注意是最后一个
    override fun onDisabled(context: Context) {
        super.onDisabled(context)
        Log.d("自定义的", "onDisabled--: ")
    }
}


